<template>
  <div>
    <Header></Header>
    <div class="exercise-read">
      <div class="exercise-read-container w1200">
        <div
          class="text-right-btns"
          v-if="
            !isReview &&
              sentenceList.length > 0 &&
              strangeSentence + familiarSentence == sentenceList.length
          "
        >
          <div class="right-btn click" @click="setStudyAgain">
            再<br />学<br />一<br />遍
          </div>
          <div class="right-btn click" @click="gotextTestPaper">
            去<br />闯<br />关
          </div>
        </div>
        <div class="container-title">
          <div class="container-box" v-if="!isReview">
            <span class="progress">
              <span>
                进度：{{ strangeSentence + familiarSentence }} /
                {{ sentenceList.length }} 句
              </span>
              <el-progress
                v-if="sentenceList.length > 0"
                :color="$store.getters.color_main"
                :show-text="false"
                :percentage="
                  parseInt(
                    ((strangeSentence + familiarSentence) /
                      sentenceList.length) *
                      100
                  )
                "
              ></el-progress>
            </span>
            <span class="number">
              <span>生句：{{ strangeSentence }}</span>
              <span>熟句：{{ familiarSentence }}</span>
            </span>
          </div>
          <div v-else></div>
          <span class="remind-text">
            <span v-if="isReview"
              ><i class="font_family icon-fslivereview mr5"></i
              >需要复习的句子，达到80分以上才算复习成功哦!</span
            >
            <!-- <span v-else>鼠标右键显示/隐藏句子</span> -->
          </span>
        </div>
        <div class="text-book-item text-book-left container-text">
          <div class="text-book-container-header">
            <span class="title">跟读训练 - {{ title }}</span>
          </div>
          <div class="reading-article mr20 text-book-contain">
            <div class="text-book-contain-box">
              <div class="check-language">
                <el-radio-group v-model="language">
                  <el-radio :label="0">EN</el-radio>
                  <el-radio :label="1">中</el-radio>
                  <el-radio :label="2">EN/中</el-radio>
                </el-radio-group>
                <div class="grade-read">
                  <span class="standard-right">标准</span>
                  <span class="general-right">一般</span>
                  <span class="read-error">不准确</span>
                  <span class="delete-error">漏读</span>
                </div>
              </div>
              <div class="text-paragraph-list">
                <div class="scorll-box">
                  <div
                    class="text-book-paragraph"
                    v-for="(item, index) in sentenceList"
                    :key="item.id"
                  >
                    <div class="name" v-if="item.name">{{ item.name }}:</div>
                    <div
                      class="paragraph click"
                      :class="[
                        playNum == index ? 'play-paragraph' : '',
                        isReview && item.is_not == 0 ? 'review-paragraph' : '',
                      ]"
                      @click="playNum = index"
                    >
                      <div
                        class="icon-review"
                        v-if="isReview && item.is_not == 0"
                      >
                        <i class="font_family icon-fslivereview"></i>
                      </div>
                      <div
                        class="content"
                        v-show="language == 0 || language == 2"
                      >
                        <span v-if="!item.result"> {{ item.content }}</span>
                        <span v-if="item.result" class="result-read">
                          <span
                            v-for="(word, index) in getCheckedContent(item)"
                            :key="index"
                            :class="[
                              word.is_err == 0 ? 'read-error' : '',
                              word.is_err == 1 ? 'delete-error' : '',
                              word.is_err == 2 && word.score >= 8
                                ? 'standard-right'
                                : '',
                              word.is_err == 2 && word.score < 8
                                ? 'general-right'
                                : '',
                            ]"
                            >{{ word.chars }}</span
                          >
                        </span>
                      </div>
                      <div
                        class="translation"
                        v-show="language == 1 || language == 2"
                      >
                        {{ item.translation }}
                      </div>
                      <div class="record" v-show="playNum == index">
                        <div
                          class="right-audio"
                          :class="hasRecording ? 'not-click' : 'click'"
                          @click="playParagraph(item.startTime, item.endTime)"
                        >
                          <i
                            v-show="!isPlayParagraph"
                            class="font_family icon-bofang"
                          ></i>
                          <i
                            v-show="isPlayParagraph"
                            class="font_family icon-zanting"
                          ></i>
                        </div>
                        <div class="audio-record">
                          <AudioRecord
                            @start="handleStart"
                            @ended="handleEnd"
                            @clickStart="audioRecordStart(item)"
                            @clickEnd="audioRecordEnd(item, index)"
                            @beforeSatrt="beforeRecordSatrt"
                            :ref="`audioRecord${item.id}-${index}`"
                            :key="item.id"
                            :type="2"
                          ></AudioRecord>
                        </div>
                        <div class="stu-audio" v-if="item.result">
                          <AudioPlay
                            :type="3"
                            :audioSrc="assetsURL + item.sAudioSrc"
                            :isAllowPause="true"
                            :disabled="hasRecording"
                          >
                            <div slot="play" class="score">
                              <span> {{ item.score }} </span>
                              <i class="font_family icon-bofang"></i>
                            </div>
                            <div slot="pause" class="playing">
                              <i class="font_family icon-zanting1"></i>
                            </div>
                          </AudioPlay>
                        </div>
                        <div
                          class=""
                          v-if="item.result"
                          v-show="playNum == index"
                        >
                          <span class="ml10">
                            完整度得分:{{ item.result.lines[0].integrity }}
                          </span>
                          <span class="ml10">
                            准确度得分:{{ item.result.lines[0].pronunciation }}
                          </span>
                          <span class="ml10">
                            流利度得分:{{ item.result.lines[0].fluency }}
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div>
      <AudioPlayText
        ref="textAudio"
        :type="3"
        :audioSrc="baseURL + audioSrc"
        @onIsPlay="acceptAudioPlay"
        :sentenceList="sentenceList"
        :playNum="playNum"
      ></AudioPlayText>
    </div>
  </div>
</template>
<script>
/**
 * 标准
 * 一般
 * 不准确
 * 漏读
 * is_err 
 *  0: 单词读的正确。
    1: 插入(多读)错误。
    2: 删除(漏读)错误。
    3: 替换(错读)错误。
 */
import Header from "@/components/Header";
import AudioRecord from "@/components/AudioRecord";
import AudioPlay from "@/components/AudioPlay";
import AudioPlayText from "../components/AudioPlay";
import {
  postParagraphRecord,
  getStudyTextList,
  getTextReview,
  postReviewRecord,
  setStudyAgain,
} from "@/api/text";
export default {
  data() {
    return {
      checkedBookData: {},
      language: 2,
      textData: {},
      sentenceList: [],
      title: "",
      audioSrc: "",
      playNum: 0,
      isPlayParagraph: false,
      unitId: null,
      category: 1,
      strangeSentence: 0,
      familiarSentence: 0,
      isReview: 0,
      reviewNum: 0,
      hasRecording: false,
    };
  },
  watch: {
    sentenceList: {
      handler(val) {
        console.log(val, 151515);
      },
      deep: true,
    },
  },
  methods: {
    // 字符串去空
    trimAll(ele) {
      if (typeof ele === "string") {
        return ele.split(/[\t\r\f\n\s]*/g).join("");
      } else {
        console.error(
          `${typeof ele} is not the expected type, but the string type is expected`
        );
      }
    },
    getCheckedContent(data) {
      console.log(data, "data11111");
      const pattern_Sy = new RegExp(
        "[`~!@#$^&*()=|{}':;',\\[\\].<>《》/\?~！@#￥……&*（）——|{}【】‘；：”“'。，、？+-/ ]|[\\\\/]"
      );
      let content = [];
      let sentenceStr = this.trimAll(data.content);
      let wordIndex=0;
      data.result.lines[0].words.forEach((item) => {
        if (item.text == "sil") return;
        let wordLength = item.text.length;
        content.push({
          chars: item.text,
          isSymbol: false,
          score: item.score,
          is_err: item.type,
        });
        wordIndex+=wordLength
        if (pattern_Sy.test(sentenceStr[wordIndex])){
           content.push({
              chars: sentenceStr[wordIndex],
              isSymbol: true,
            });
            wordIndex+=1
        }else{
          content.push({
              chars: " ",
              isSymbol: true,
            });
        }
      });
      console.log(content, "content");
      return content;
    },
    acceptAudioPlay(data) {
      this.isPlayParagraph = data;
    },
    getText() {
      let params = {
        bookId: this.checkedBookData.book_id,
        unitId: this.unitId,
        category: this.category,
      };
      getStudyTextList(params).then((res) => {
        if (res.code == 200 && res.data) {
          this.textData = res.data;
          this.strangeSentence = res.data.list.filter((item) => {
            return item.is_strange == 1;
          }).length;
          this.familiarSentence = res.data.list.filter((item) => {
            return item.is_strange == 0;
          }).length;
          this.sentenceList = res.data.list.map((item) => {
            let detail;
            // let sAudioSrc;
            // let reg1 = new RegExp("\\", "g")
            // sAudioSrc =item.student_url.replace(reg1, "/")
            if (item.detail) {
              let reg = new RegExp("/", "g"); // 加'g'，删除字符串里所有的"a"
              detail = JSON.parse(item.detail.replace(reg, ""));
            } else {
              detail = null;
            }
            return {
              id: item.sentence_id,
              content: item.content,
              translation: item.translation,
              name: item.name,
              startTime: item.start_time,
              endTime: item.end_time,
              sAudioSrc: item.student_url,
              score: item.score ? item.score : 0,
              result: detail,
            };
          });
          this.audioSrc = this.textData.audio_src;
        }
      });
    },

    getReviewText(nextUnitId) {
      let params = {};
      let unitId = null;
      if (nextUnitId || nextUnitId === null) {
        unitId = nextUnitId;
      } else if (this.unitId) {
        unitId = this.unitId;
      } else if (this.textData.unit_id) {
        unitId = this.textData.unit_id;
      }
      let data = {
        book_id: this.checkedBookData.book_id,
        unit_id: unitId,
        category: this.category,
      };

      getTextReview(params, data).then((res) => {
        if (res.code == 200 && res.data && res.data[0]) {
          if (res.data[0].unit_id != this.textData.unit_id) {
            this.playNum = 0;
          }
          this.textData = res.data[0];
          this.sentenceList = res.data[0].list.map((item) => {
            return {
              id: item.sentence_id,
              content: item.content,
              translation: item.translation,
              name: item.name,
              startTime: item.start_time,
              endTime: item.end_time,
              sAudioSrc: item.student_url,
              score: item.score ? item.score : 0,
              result: item.detail ? JSON.parse(item.detail) : null,
              is_not: item.is_not,
            };
          });
          this.audioSrc = this.textData.audio_src;
          this.reviewNum = this.sentenceList.filter((item) => {
            return item.is_not == 0;
          }).length;
        } else if (res.code == 405) {
          // this.unitId 本单元复习
          // unitId==null 全部复习为null
          if (this.unitId || unitId === null) {
            this.$alert(
              `${this.unitId ? "本单元" : ""}跟读训练已复习完成`,
              "消息提示",
              {
                confirmButtonText: "确定",
                callback: () => {
                  this.goStudyCenter();
                },
              }
            );
          } else {
            setTimeout(() => {
              this.getReviewText(null);
            }, 1000);
          }
        }
      });
    },
    goStudyCenter() {
      this.$router.push({
        name: "textStudyCenter",
      });
    },
    playParagraph(startTime, endTime) {
      if (this.hasRecording) {
        return;
      }
      if (!this.isPlayParagraph) {
        this.playParagraphAudio(startTime, endTime);
      } else {
        this.pauseParagraphAudio();
      }
    },
    playParagraphAudio(startTime, endTime) {
      this.$refs.textAudio.playAudio(startTime, endTime);
    },
    pauseParagraphAudio() {
      this.$refs.textAudio.pauseAudio();
    },

    handleStart() {
      this.hasRecording = true;
    },
    handleEnd() {
      this.hasRecording = false;
    },
    // 点击录音开始前的回调
    beforeRecordSatrt() {
      this.$pauseAllAudio();
      console.log(1);
      this.sentenceList.forEach((item, index) => {
        console.log(2);
        if (
          this.$refs[`audioRecord${item.id}-${index}`] &&
          this.$refs[`audioRecord${item.id}-${index}`][0]
        ) {
          this.$refs[`audioRecord${item.id}-${index}`][0].stopRecorder();
        }
      });
    },
    // 点击开始录音的回调
    audioRecordStart() {
      console.log("点击开始");
      //
    },
    // 点击结束录音的回调
    // sentence_id=181&content=I'm Mike.
    // http://localhost:8101/sound/save?word_id=121&word_name=testcc&is_child=1&accent=1
    audioRecordEnd(sentenceData, index) {
      console.log("点击结束");
      let blob = this.$refs[
        `audioRecord${sentenceData.id}-${index}`
      ][0].getMp3Data();
      let duration = this.$refs[`audioRecord${sentenceData.id}-${index}`][0]
        .recorder.duration;
      let file = new window.File([blob], sentenceData.id + ".mp3", {
        type: blob.type,
      });
      let formData = new FormData();
      // console.log(file, "file");
      formData.append("sound_file", file);
      formData.append("sentence_id", sentenceData.id);
      formData.append("content", sentenceData.content);
      formData.append("unit_id", this.textData.unit_id);
      formData.append("category", this.category);
      formData.append("book_id", this.checkedBookData.book_id);

      // type:1 读 type:2背诵
      if (this.isReview && sentenceData.is_not == 0) {
        this.postReviewRecord({ formData, sentenceData });
      } else {
        this.postParagraphRecord({ formData, duration, sentenceData });
      }
    },
    postReviewRecord({ formData, sentenceData }) {
      postReviewRecord({}, formData).then((res) => {
        if (res.code == 200 && res.data) {
          this.reviewNum--;
          sentenceData.score = res.data.score;
          this.getStudyText();
        }
      });
    },
    postParagraphRecord({ formData, duration, sentenceData }) {
      formData.append("is_child", 0);
      formData.append("accent", 1);
      formData.append("type", this.category);
      // formData.append("group_id", this.textData.group_id);
      formData.append("use_time", parseInt(duration));
      postParagraphRecord({}, formData).then((res) => {
        if (res.code == 200 && res.data) {
          sentenceData.score = res.data.score;
          this.getStudyText();
        }
      });
    },
    /**
     *  获取麦克风权限
     * */
    getPermission() {
      this.$Recorder.getPermission().then(
        () => {
          console.log("获取权限成功");
        },
        (error) => {
          console.log(`${error.name} : ${error.message}`);
          if (error.name == "NotAllowedError") {
            this.$message({
              type: "error",
              message: `没有使用麦克风的权限`,
            });
          } else if (
            error.name == "NotFoundError" &&
            error.message == "Requested device not found"
          ) {
            this.$message({
              type: "error",
              message: `没有找到麦克风`,
            });
          } else {
            this.$message({
              type: "error",
              message: `${error.name} : ${error.message}`,
            });
          }
        }
      );
    },
    getStudyText() {
      if (this.isReview) {
        this.getReviewText();
      } else {
        this.getText();
      }
    },
    gotextTestPaper() {
      this.$router.push({
        name: "textTestPaper",
        query: {
          type: this.category,
          unitId: this.unitId,
        },
      });
    },
    setStudyAgain() {
      this.$confirm(
        `再学一遍会将此模块的进度重置，请确认是否再学一遍`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          showClose: true,
          distinguishCancelAndClose: true,
        }
      )
        .then(() => {
          let data = {
            bookId: this.checkedBookData.book_id,
            unitId: this.unitId,
            category: this.category,
          };
          setStudyAgain(data).then((res) => {
            if (res.code == 200) {
              this.$alert("重置进度成功", "提示");
              this.getStudyText();
            }
          });
        })
        .catch(() => {});
    },
  },

  created() {
    this.checkedBookData = JSON.parse(localStorage.getItem("bookData"));
    this.unitId = this.$route.query.unitId
      ? Number(this.$route.query.unitId)
      : null;
    this.title = localStorage.getItem("checkedUnit")
      ? JSON.parse(localStorage.getItem("checkedUnit")).title
      : "";
    this.isReview = this.$route.query.isReview == 1 ? 1 : 0;
    this.getStudyText();
  },
  mounted() {
    // this.getPermission();
  },
  components: {
    Header,
    AudioRecord,
    AudioPlay,
    AudioPlayText,
  },
};
</script>
